<?php
// +----------------------------------------------------------------------
// 任务管理系统
// +----------------------------------------------------------------------

namespace app\task\controller;

use api\ggz\model\CompanyModel;
use app\admin\model\UserModel;
use cmf\controller\HomeBaseController;
use app\task\service\Auth;
use app\task\model\TaskModel;
use app\task\service\TaskService;
use think\Exception;
use think\facade\Db;
use think\Request;
use think\Validate;
use think\Response;
use api\ggz\model\PatentModel;
use api\ggz\model\MarkModel;
use api\ggz\model\QualificationsModel;

class TaskController extends HomeBaseController
{

    /**公司列表
     * @return mixed
     */
    public function companyList()
    {
        $bulletin = TaskService::getCompany();
        return $this->assign("data", $bulletin)->fetch();
    }

    /**公司审核
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function companyVerify(Request $request,CompanyModel $companyModel){
        try{
            $companyModel->modify(['id'=>$request->param('id')],['verify'=>$request->param('val')]);
        }catch (Exception $e){
            return $this->error('操作失败,'.$e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**资质交易列表
     * @return mixed
     */
    public function qualification(){
        $qualification = TaskService::getQualification();
        return $this->assign("data", $qualification)->fetch();
    }
    /**资质交易审核
     * @param Request $request
     * @param QualificationsModel $Qualification
     */
    public function qualificationVerify(Request $request,QualificationsModel $Qualification){
        try{
            $Qualification->modify(['id'=>$request->param('id')],['verify'=>$request->param('val')]);
        }catch (Exception $e){
            return $this->error('操作失败,'.$e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**商标交易列表
     * @return mixed
     */
    public function mark(){
        $mark = TaskService::getMark();
        return $this->assign("data", $mark)->fetch();
    }

    /**商标交易审核
     * @param Request $request
     * @param MarkModel $MarkModel
     */
    public function markVerify(Request $request,MarkModel $MarkModel){
        try{
            $MarkModel->modify(['id'=>$request->param('id')],['verify'=>$request->param('val')]);
        }catch (Exception $e){
            return $this->error('操作失败,'.$e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 专利交易列表
     * @return mixed
     */
    public function patent(){
        $Patent = TaskService::getPatent();
        return $this->assign("data", $Patent)->fetch();
    }
    /**专利交易审核
     * @param Request $request
     * @param PatentModel $Patent
     */
    public function patentVerify(Request $request,PatentModel $Patent){
        try{
            $Patent->modify(['id'=>$request->param('id')],['verify'=>$request->param('val')]);
        }catch (Exception $e){
            return $this->error('操作失败,'.$e->getMessage());
        }
        return $this->success('操作成功');
    }

    public function patentDetail(Request $request,PatentModel $PatentModel){
        $data   =   $PatentModel->getDataById($request->param('id'));
        return $this->assign("data", $data)->fetch();
    }

    /**公司详情
     * @param Request $request
     * @param CompanyModel $companyModel
     * @return mixed
     */
    public function companyDetail(Request $request,CompanyModel $companyModel){
        $data   =   $companyModel->getDataById($request->param('id'));
        return $this->assign("data", $data)->fetch();
    }

    /**资质交易详细信息表
     * @param Request $request
     * @param Qualification $Qualification
     * @return mixed
     */
    public function qualificationDetail(Request $request,QualificationsModel $Qualification){
        $data   =   $Qualification->getDataById($request->param('id'));
        return $this->assign("data", $data)->fetch();
    }

    public function markDetail(Request $request,MarkModel $MarkModel){
        $data   =   $MarkModel->getDataById($request->param('id'));
        return $this->assign("data", $data)->fetch();
    }
    public function getNextDeparment()
    {
        $condition = $this->request->param();
        $class = $condition['class'];
        unset($condition['class']);
        if ($condition) {
            return $this->result(TaskService::getNextDeparment($condition, $class));
        }
        return false;
    }

    public function getChildWxDepartment()
    {
        $id = $this->request->param('id');
        if ($id) {
            $data['department'] = TaskService::getChildWxDepartment($id);
            $data['user'] = TaskService::getUserByDepartment($id);
            return $this->result($data);
        }
        return false;
    }

    public function getUserDeparment()
    {
        $department = $this->request->param();
        if ($department) {
            $departmentid = TaskService::getDepartmentId($department);
            return $this->result(TaskService::getUserByDepartment($departmentid));
        }
    }

    public function getDepartment()
    {
        $id = $this->request->param('id');
        return response(TaskService::getDepartment($id));
    }

    public function getUserByDepartment()
    {
        $id = $this->request->param('id');
        return $this->result(TaskService::getUserByDepartment($id));
    }

    public function getUserByName()
    {
        $name = $this->request->param('name');
        return $this->result(TaskService::getUserByName($name));
    }


    /**任务审核
     * @return mixed
     */
    public function examine()
    {
        $taskid = $this->request->param('taskid');
        $data = TaskService::getTaskDetail($taskid);
        //任务动态信息
        $dynamic = TaskService::getTaskDynamic($taskid);
        //var_dump($dynamic);die;
        return $this->assign("list", $data)->assign('dynamic', $dynamic)->fetch();
    }

    public function getUserById()
    {
        if ($uid = $this->request->param('uid')) {
            $data = (new UserModel())->field('id,user_nickname,job,label')->where(['id' => $uid])->find();
            return $this->result($data);
        }
        return $this->result('');
    }


    /**统计
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function statistics()
    {
        $para = $this->request->param();
        $para = array_filter($para, 'filter');
        $uid = cmf_get_current_admin_id();
        $where[] = ['b.user_id', '=', $uid];
        if (isset($para['task_start_time'])) $where[] = ['a.task_start_time', '>=', strtotime($para['task_start_time'])];
        if (isset($para['task_end_time'])) $where[] = ['a.task_end_time', '<=', strtotime($para['task_end_time'])];
        $data = Db::table('task_task')
            ->field('a.task_status,sum(a.task_mark) as score')
            ->alias('a')
            ->join('task_task_user b', 'a.task_id=b.task_id', 'left')
            ->group('a.task_status')
            ->where($where)
            ->select()->toArray();
        $count = Db::table('task_task')
            ->alias('a')
            ->field('a.task_status,count(*) as count')
            ->join('task_task_user b', 'a.task_id=b.task_id', 'left')
            ->group('a.task_status')
            ->where($where)
            ->select()->toArray();
        foreach ($data as $key => $val) {
            $data[$key]['name'] = getStatus($val['task_status']);
            foreach ($count as $ke => $va) {
                if ($va['task_status'] == $val['task_status']) {
                    $data[$key]['count'] = $va['count'];
                }
            }
        }
        return $this->assign("list", $data)->fetch();
    }


    /**
     * 获取公告详情
     */
    public function getBulletin()
    {
        $id = $this->request->param('id');
        if ($id) {
            $data = Db::name('bulletin')->where("bulletin_id=$id")->find();
            return '<div class="admin-content am-padding am-padding-top-0">
                    <div class="task-list">
                        <h2 class="am-margin-top-sm am-margin-bottom-sm">' . $data['bulletin_title'] . '</h2>
                    </div>
                    <article class="am-article am-margin-top-sm">
                                <div class="am-article-bd">
                           ' . htmlspecialchars_decode($data['bulletin_content']) . '       </div>
                     </article>
                        </div>';
        }
        return "";
    }


    /**添加公告
     * @return mixed|void
     */
    public function addBulletin()
    {
        $post = $this->request->param();
        if ($this->request->isPost()) {
            $data['bulletin_listsort'] = $post['bulletin_listsort'];
            $data['bulletin_title'] = $post['bulletin_title'];
            $data['bulletin_content'] = $post['content'];
            $data['bulletin_createtime'] = strtotime($post['createtime']);
            if (TaskService::addBulletin($data)) {
                return TaskService::result(200, '公告成功', url("task/task/bulletin"));
            }
            return TaskService::result(500, '公告失败', url("task/task/bulletin"));
        }
        return $this->fetch();
    }

    /**编辑公告
     * @return mixed|void
     */
    public function editBulletin()
    {
        if ($id = $this->request->param('bulletin_id')) {
            if ($this->request->isPost()) {
                $post = $this->request->param();
                $data['bulletin_listsort'] = $post['bulletin_listsort'];
                $data['bulletin_title'] = $post['bulletin_title'];
                $data['bulletin_content'] = $post['content'];
                $data['bulletin_createtime'] = strtotime($post['createtime']);
                if (TaskService::updateBulletin($id, $data)) {
                    return TaskService::result(200, '公告成功', url("task/task/bulletin"));
                }
                return TaskService::result(500, '公告失败', url("task/task/bulletin"));
            }
            $data = TaskService::getBulletin($id);
            return $this->assign('data', $data)->fetch();
        }
    }

    /**删除公告
     * @return mixed|void
     */
    public function delBulletin()
    {
        if ($id = $this->request->param('bulletin_id')) {
            if (TaskService::delBulletin($id)) {
                return TaskService::result(200, '删除公告成功', url("task/task/bulletin"));
            }
            return TaskService::result(500, '删除公告失败', url("task/task/bulletin"));
        }

    }

    public function exportUser()
    {
        if ($this->request->isPost()) {
            $roleid = $this->request->param('role');
            $token = TaskService::gettoken();
            /* $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$token;
             $re = file_get_contents($url);
             $val = json_decode($re,true);
             if(!$this->request->param('page')){
                 Db::name("wxdepartment")->update(['isup'=>0]);
             }*/
            if ($this->request->param('status') == 1) {
                Db::name("wxdepartment")->where(['isup' => 1])->update(['isup' => 0]);
            }
            $page = $this->request->param('page') ? $this->request->param('page') : 0;
            if (!$count = $this->request->param('count')) {
                $count = Db::name("wxdepartment")->where("isup=0")->count();
            }
            $com = Db::name("wxdepartment")->where("isup=0")->limit(10)->order("id asc")->select();
            if (isset($com)) {
                foreach ($com as $key => $val) {
                    $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" . $token . "&department_id=" . $val['id'];
                    $re = file_get_contents($url);
                    $val1 = json_decode($re, true);
                    if (isset($val1['userlist'])) {
                        foreach ($val1['userlist'] as $ke => $va) {
                            $data['user_login'] = $va['userid'];
                            $data['code'] = $va['userid'];
                            $data['user_nickname'] = $va['name'];
                            //$data['role_id'] = 2;
                            $data['user_status'] = 1;
                            $data['user_pass'] = '###820798c3e811eaad5783ea010ce471ea';
                            $data['departmentid'] = $val['id'];

                            $data['user_email'] = $va['email'];
                            $data['mobile'] = $va['mobile'];
                            $data['job'] = $va['position'];

                            $data['label'] = $va['alias'];
                            $data['avatar'] = $va['avatar'];
                            $data['sex'] = $va['gender'];
                            if (Db::name("user")->where(['user_login' => $va['userid']])->find()) {
                                Db::name("user")->where(['user_login' => $va['userid']])->update($data);
                            } else {
                                Db::startTrans();
                                try {
                                    $uid = Db::name("user")->insertGetId($data);
                                    Db::name("role_user")->insert(['role_id' => $roleid, 'user_id' => $uid]);
                                    Db::commit();
                                } catch (\Exception $e) {
                                    Db::rollback();
                                    echo $e->getMessage();
                                }

                            }
                            unset($data);
                            unset($temp);
                        }
                    }
                    unset($data);
                    Db::name("wxdepartment")->where("id=" . $val['id'])->update(['isup' => 1]);
                }

            }
            //echo $count;die;
            if ($count == 0) {
                return TaskService::result(200, '成功！', url("task/task/exportUser"), ['page' => $page + 1, 'total' => ceil($count / 10), 'count' => $count, 'speed' => 100, 'role' => $roleid]);
            }
            $speed = floor((($page + 1) * 1000) / $count);
            $speed = $speed > 100 ? 100 : $speed;
            return TaskService::result(200, '成功！', url("task/task/exportUser"), ['page' => $page + 1, 'total' => ceil($count / 10), 'count' => $count, 'role' => $roleid, 'speed' => $count > 10 ? $speed : 100]);
            //return json_encode();
        }
        $role = Db::name("role")->field('id,name')->where(['status' => 1])->select();
        $info = Db::name('user')->alias('a')->field('a.*,b.name as department_name')->join('wxdepartment b', 'a.departmentid=b.id', 'left')->where('a.id > 1')->order('a.id asc')->paginate(10);
        return $this->assign('list', $info)->assign('role', $role)->fetch();
    }

    public function exportDepartment()
    {

        if ($this->request->isPost()) {
            $token = TaskService::gettoken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" . $token;
            $re = file_get_contents($url);
            $val = json_decode($re, true);
            if (isset($val['department'])) {
                foreach ($val['department'] as $key => $val) {
                    $data['id'] = $val['id'];
                    $data['name'] = $val['name'];
                    $data['parentid'] = $val['parentid'];
                    $data['order'] = $val['order'];
                    $data['update_time'] = date("Y-m-d H:i:s");
                    if (Db::name("wxdepartment")->where(['id' => $val['id']])->find()) {
                        continue;
                    }
                    Db::name("wxdepartment")->insert($data);
                    unset($data);
                }

            }
        }
        $info = Db::name('wxdepartment')->order('order asc')->paginate(10);
        return $this->assign('list', $info)->fetch();
    }

    public function taskTransfer()
    {
        $taskid = $this->request->param('taskid');
        if ($taskid) {
            $info = TaskService::getTaskDetail($taskid);
        }
        if ($this->request->isPost()) {
            $taskid = $this->request->param('transferid');
            $userid = $this->request->param('userid');
            if (!$userid) {
                return $this->error('转移失败，找不到改用户');
            }
            $uid = cmf_get_current_admin_id();
            if ($info['task_create_id'] == $uid) {
                if (TaskService::updateTaskUser($taskid, $userid)) {
                    $data['task_dynamic_user_id'] = $uid;
                    $data['task_dynamic_task_id'] = $taskid;
                    $data['task_dynamic_content'] = TaskService::getUser($uid, 'user_nickname') . '修改任务归属人为：' . TaskService::getUser($userid, 'user_nickname');
                    $data['task_dynamic_createtime'] = time();
                    TaskService::addTaskDynamic($data);
                    return $this->success('转移成功!');
                }
            } else {
                $data['taskid'] = $taskid;
                $data['applicant'] = $uid;
                $data['acceptid'] = $userid;
                if (TaskService::addTaskTransfer($data)) {
                    $Dynamic['task_dynamic_user_id'] = $uid;
                    $Dynamic['task_dynamic_task_id'] = $taskid;
                    $Dynamic['task_dynamic_content'] = TaskService::getUser($uid, 'user_nickname') . '申请任务转移给' . TaskService::getUser($userid, 'user_nickname');
                    $Dynamic['task_dynamic_createtime'] = time();
                    TaskService::addTaskDynamic($Dynamic);
                    return $this->success('申请成功!等待接收人确认');
                }
            }
            return $this->error('转移失败，请稍后操作');
        }
        $dynamic = TaskService::getTaskDynamic($taskid);
        return $this->assign("list", $info)->assign('dynamic', $dynamic)->fetch();
    }

    public function transferList()
    {
        $uid = cmf_get_current_admin_id();
        $info = DB::name('transfer')
            ->alias('a')
            ->join('task b', 'a.taskid=b.task_id', 'left')
            ->where("a.acceptid=$uid")
            ->select()->toArray();
        return $this->assign('info', $info)->fetch();
    }

    public function doTransfer()
    {
        $id = $this->request->param('id');
        $transfer_status = $this->request->param('transfer_status');
        if ($id && $transfer_status) {
            $uid = cmf_get_current_admin_id();
            $task = Db::table('task_transfer')
                ->alias('a')
                ->join('task_task b', 'a.taskid=b.task_id', 'left')
                ->join('task_task_user c', "b.task_id=c.task_id", 'left')
                ->where("a.id=$id")
                ->find();
            //var_dump($task);die;
            $data['task_dynamic_user_id'] = $uid;
            $data['task_dynamic_task_id'] = $task['task_id'];
            if ($transfer_status == 1) {
                $data['task_dynamic_content'] = TaskService::getUser($uid, 'user_nickname') . '接受了转移任务';
            } else {
                $data['task_dynamic_content'] = TaskService::getUser($uid, 'user_nickname') . '拒绝了转移任务';
            }
            $data['task_dynamic_createtime'] = time();
            Db::startTrans();
            try {
                TaskService::addTaskDynamic($data);
                $re = Db::name('transfer')->where(['id' => $id])->update(['transfer_status' => $transfer_status, 'update_time' => time()]);
                $re = Db::name('task_user')->where(['task_id' => $task['task_id']])->update(['user_id' => $task['acceptid']]);
                Db::commit();
                return $this->success('success');
            } catch (\think\Exception $e) {
                //Db::rollback();
                //echo $e->getMessage();
                return $this->error('error');
            }
        }
    }

    public function modifyDepartment()
    {
        $id = $this->request->param('id');
        if ($id) {
            if ($this->request->isPost()) {
                $post = $this->request->param('post');
                $departmentid = TaskService::getDepartmentId($post);
                return TaskService::setDepartment($id, $departmentid) ? $this->success('修改成功') : $this->error('修改失败');
            }
            $data = TaskService::getDepartmentByUid($id);
            return $this->assign("user", $data)->assign('getDepartment', TaskService::getDepartment())->fetch();
        }
        return false;
    }

    public function delLog()
    {
        $data = Db::name('operation_log')
            ->alias('a')
            ->field('a.*,b.user_nickname')
            ->join('user b', 'a.userid=b.id', 'left')
            ->order('a.id desc')->paginate(10);
        $data_array = $data->toArray();
        $list = $data_array['data'];
        //print_r($data_array);die;
        foreach ($list as $key => $val) {
            $list["$key"]['redundancy'] = json_decode($val['redundancy'], true);
        }
        return $this->assign("data", $list)->assign('data_array', $data)->fetch();
    }

    public function getLabel()
    {
        $name = $this->request->param('name');
        if ($name) {
            $re = Db::name('user')->field('label')->where("label like '%$name%'")->group('label')->select()->toArray();
            return $this->result($re);
        }
    }
}
